package controller;
import courses.Course;
import files.FileInfoReader;
import roles.Admin;
import roles.Professor;
import roles.Student;

import java.util.List;
import java.util.Optional;
import java.util.Scanner;

/**
 * 控制类
 */
public class Controller {

    /**
     * 初始化输入
     */
    private static Scanner scanner=new Scanner(System.in);

    /**
     * 初始化管理员集合
     */
    private static List<Admin> adminList=null;

    /**
     * 初始化学生集合
     */
    private static List<Student> studentList=null;

    /**
     * 初始化教授集合
     */
    private static List<Professor> professorList=null;

    /**
     * 初始化课程集合
     */
    private static List<Course> courseList=null;


    /**
     * 初始化加载文件数据
     */
    static {
        adminList= FileInfoReader.getFileAdminInfo();
        studentList=FileInfoReader.getFileStudentInfo();
        professorList=FileInfoReader.getFileProfInfo();
        courseList=FileInfoReader.getFileCourseInfo();
    }

    /**
     * 程序入口启动
     * @param args
     */
    public static void main(String[] args) {
        mainStr();
    }

    /**
     * 主页面
     */
    private static void mainStr(){
        while (true){
            System.out.println("--------------------");
            System.out.println("Students Management System");
            System.out.println("--------------------");
            System.out.println("1 -- Login as student");
            System.out.println("2 -- Login as professor");
            System.out.println("3 -- Login as admin");
            System.out.println("4 -- Quit the system");
            System.out.println("Please enter your option, eq. '1'");
            String option=scanner.next();
            if(option.equals("1")){//Login as student
                studentLoginMain();;
            }else if(option.equals("2")){//Login as professor
                professorLoginMain();
            }else if(option.equals("3")){//Login as admin
                adminLoginMain();
            }else if(option.equals("4")){//Quit the system
                return;
            }else{
                continue;
            }
            break;
        }
    }

    /**
     * 管理员端登录
     */
    private static void adminLoginMain() {
        while (true){
            System.out.println("Please enter your username, or type 'q' to quit.");
            String username=scanner.next();
            if (username.equalsIgnoreCase("q")) {
                return; //
            }
            System.out.println("Please enter your password, or type 'q' to quit.");
            String password=scanner.next();
            if (password.equalsIgnoreCase("q")) {
                return; //
            }
            // 使用 Stream 进行匹配和返回对象
            Optional<Admin> matchedAccount = adminList.stream()
                    .filter(admin -> admin.getAccount().equals(username) && admin.getPassword().equals(password))
                    .findFirst();
            // 检查是否存在匹配的账号
            if (matchedAccount.isPresent()) {
                System.out.println("--------------------");
                System.out.println("Welcome "+matchedAccount.get().getName());
                System.out.println("--------------------");
                adminMain();
                break;
            } else {
                System.out.println("--------------------");
                System.out.println("Error Password");
                System.out.println("--------------------");
                continue;
            }
        }
    }

    /**
     * 管理员主页面
     */
    private static void adminMain(){
        while (true){
            System.out.println("1 -- View all courses");
            System.out.println("2 -- Add new courses");
            System.out.println("3 -- Delete courses");
            System.out.println("4 -- Add new professor");
            System.out.println("5 -- Delete professor");
            System.out.println("6 -- Add new student");
            System.out.println("7 -- Delete student");
            System.out.println("8 -- Return to previous menu");
            System.out.println("Please enter your option, eq. '1'");
            String option=scanner.next();
            if(option.equals("1")){//View all courses
                showCourse();
            }else if(option.equals("2")){//Add new courses
                addCourseMain();
            }else if(option.equals("3")){//Delete courses
                deleteCourse();
            }else if(option.equals("4")){//Add new professor
                addProfessorMain();
            }else if(option.equals("5")){//Delete professor
                deleteProfessorMain();
            }else if(option.equals("6")){//Add new professor
                addStudentMain();
            }else if(option.equals("7")){//Delete student
                deleteStudentMain();
            }else if(option.equals("8")){//Return to previous menu
                mainStr();
            }else{
                continue;
            }
            adminMain();
            break;
        }

    }

    /**
     * 查询所有课程
     */
    private static void showCourse() {
        for (Course course : courseList) {
            System.out.println( course.getCourseid() + "," + course.getCoursename()+ "," + course.getLecturer()
                    + "," + course.getClassday()+ "," + course.getBegintime()+ "," + course.getEndtime()+ "," + course.getMaxNum());
        }
    }

    /**
     * 根据教授名字查询他所有课程
     */
    private static void showCourseName(String name) {
        List<Course> list=Course.exitCourseName(name,courseList);
        for (Course course : list) {
            System.out.println( course.getCourseid() + "," + course.getCoursename()+ "," + course.getLecturer()
                    + "," + course.getClassday()+ "," + course.getBegintime()+ "," + course.getEndtime()+ "," + course.getMaxNum());
        }
    }

    /**
     * 根据课程ID获取学生
     */
    private static void showStudentCourse() {
        System.out.println("Please enter the course ID, eq. 'CIS519. Or type 'q' to quit.'");
        String courseId=scanner.next();
        if (courseId.equalsIgnoreCase("q")) {
            return; //
        }
        List<Student> list=Student.exitStudentCourseId(courseId,studentList);
        for (Student student : list) {
            System.out.println( student.getId() + "," + student.getName()+ "," + student.getAccount()
                    + "," + student.getPassword()+ "," + student.getScoreclassid());
        }
    }

    /**
     * 删除课程
     */
    private static void deleteCourse() {
        String id="";
        while (true){
            System.out.println("Please enter the course's ID, or type 'q' to quit");
            id=scanner.next();
            if (id.equalsIgnoreCase("q")) {
                return; //
            }
            //检测ID是否存在
            Course course=Course.exitCourseId(id,courseList);
            if(course==null){//不存在当前课程
                System.out.println("The ID no exist");
                continue;
            }
            //执行删除
            courseList.removeIf(person -> person.getCourseid().equals(course.getCourseid()));
            System.out.println("Successfully delete the new course:"+course.getCourseid() +" " +course.getCoursename());
            break;
        }
    }

    /**
     * 删除学生
     */
    private static void deleteStudentMain() {
        String id="";
        while (true){
            System.out.println("Please enter the student's ID, or type 'q' to quit");
            id=scanner.next();
            if (id.equalsIgnoreCase("q")) {
                return; //
            }
            //检测ID是否存在
            Student student=Student.exitStudentId(id,studentList);
            if(student==null){//不存在当前教授
                System.out.println("The ID no exist");
                continue;
            }
            //执行删除
            studentList.removeIf(person -> person.getId().equals(student.getId()));
            System.out.println("Successfully delete the new student:"+student.getId() +" " +student.getName());
            break;
        }
    }

    /**
     * 删除教授
     */
    private static void deleteProfessorMain() {
        String id="";
        while (true){
            System.out.println("Please enter the professor's ID, or type 'q' to quit");
            id=scanner.next();
            if (id.equalsIgnoreCase("q")) {
                return; //
            }
            //检测ID是否存在
            Professor professor=Professor.exitProfessorId(id,professorList);
            if(professor==null){//不存在当前教授
                System.out.println("The ID no exist");
                continue;
            }
            //执行删除
            professorList.removeIf(person -> person.getId().equals(professor.getId()));
            System.out.println("Successfully delete the new professor:"+professor.getId() +" " +professor.getName());
            break;
        }
    }

    /**
     * 添加学生
     */
    private static void addStudentMain() {
        String id="";
        String username="";
        while (true){
            System.out.println("Please enter the student's ID, or type 'q' to quit");
            id=scanner.next();
            if (id.equalsIgnoreCase("q")) {
                return; //
            }
            //检测学生ID是否存在
            Student student=Student.exitStudentId(id,studentList);
            if(student!=null){
                System.out.println("The ID already exist");
                continue;
            }
            break;
        }
        System.out.println("Please enter the student's name, or type 'q' to end");
        String name=scanner.next();
        if (name.equalsIgnoreCase("q")) {
            return; //
        }
        while (true){
            System.out.println("Please enter a username");
            username=scanner.next();
            //检测用户名是否存在
            Student professor=Student.exitStudentName(username,studentList);
            if(professor!=null){
                System.out.println("The username you entered is not available.");
                continue;
            }
            break;
        }
        System.out.println("Please enter a password");
        String password=scanner.next();
        System.out.println("Please enter ID of a course which this student already took, one in a time Type 'q' to quit, type 'n' to stop adding.");
        String course=scanner.next();
        System.out.println("Please enter the grade,eg,'A'");
        String grade=scanner.next();
        studentList.add(new Student(id,name,username,password,course+":"+grade));
        System.out.println("Successfully added the new student:"+id +" " +name);
    }

    /**
     * 添加课程
     */
    public static void addCourseMain(){
        String courseid="";
        while (true){
            System.out.println("Please enter the course ID, or type 'q' to end.");
            courseid=scanner.next();
            //检测当前课程ID是否存在系统
            Course course=Course.exitCourseId(courseid,courseList);
            if(course!=null){
                System.out.println("The course already exist");
                continue;
            }
            break;
        }
        System.out.println("Please enter the course name, or type 'q' to end.");
        String coursename=scanner.next();
        System.out.println("Please enter the course start time, or type 'q' to end. eq. '19:00'");
        String begintime=scanner.next();
        System.out.println("Please enter the course end time, or type 'q' to end. eq. '19:00'");
        String endtime=scanner.next();
        System.out.println("Please enter the course date, or type 'q' to end. eq. 'VM'");
        String classday=scanner.next();
        System.out.println("Please enter the course capacity, or type 'q' to end. eq. '72'");
        String maxNum=scanner.next();
        System.out.println("Please enter the course lecturer's id, or type 'q' to end. eq. '001'");
        String lecturer=scanner.next();
        //添加规则，需要检测教授ID是否存在，系统，如果存在，则直接添加成功，否则需要先添加教授，在添加课程
        Professor professor=Professor.exitProfessorId(lecturer,professorList);
        if(professor==null){//教授不存在，调用添加教授的接口
            addProfessorMain();
        }
        courseList.add(new Course(courseid,coursename,lecturer,classday,begintime,endtime,maxNum));
        System.out.println("Successfully added the new course："+courseid +"|"+coursename+", "+begintime+"-"+endtime+" on "+classday+", with course capacity："+maxNum+"students：0,lecturer：Professor "+lecturer);
    }


    /**
     * 添加教授
     */
    private static void addProfessorMain(){
        String id="";
        String username="";
        while (true){
            System.out.println("Please enter the professor's ID, or type 'q' to quit");
            id=scanner.next();
            if (id.equalsIgnoreCase("q")) {
                return; //
            }
            //检测教授ID是否存在
            Professor professor=Professor.exitProfessorId(id,professorList);
            if(professor!=null){
                System.out.println("The ID already exist");
                continue;
            }
            break;
        }
        System.out.println("Please enter the professor's name, or type 'q' to end");
        String name=scanner.next();
        if (name.equalsIgnoreCase("q")) {
            return; //
        }
        while (true){
            System.out.println("Please enter a username");
            username=scanner.next();
            //检测教授用户名是否存在
            Professor professor=Professor.exitProfessorName(username,professorList);
            if(professor!=null){
                System.out.println("The username you entered is not available.");
                continue;
            }
            break;
        }
        System.out.println("Please enter a password");
        String password=scanner.next();
        professorList.add(new Professor(id,name,username,password));
        System.out.println("Successfully added the new professor:"+id +" " +name);
    }


    /**
     * 教授端登录
     */
    private static void professorLoginMain() {
        while (true){
            System.out.println("Please enter your username, or type 'q' to quit.");
            String username=scanner.next();
            if (username.equalsIgnoreCase("q")) {
                return; //
            }
            System.out.println("Please enter your password, or type 'q' to quit.");
            String password=scanner.next();
            if (password.equalsIgnoreCase("q")) {
                return; //
            }
            // 使用 Stream 进行匹配和返回对象
            Optional<Professor> matchedAccount = professorList.stream()
                    .filter(professor -> professor.getAccount().equals(username) && professor.getPassword().equals(password))
                    .findFirst();
            // 检查是否存在匹配的账号
            if (matchedAccount.isPresent()) {
                System.out.println("--------------------");
                System.out.println("Welcome "+matchedAccount.get().getName());
                System.out.println("--------------------");
                professorMain(matchedAccount.get().getName());
                break;
            } else {
                System.out.println("--------------------");
                System.out.println("Error Password");
                System.out.println("--------------------");
                continue;
            }
        }
    }

    /**
     * 教授端业务
     */
    private static void professorMain(String name){
        while (true){
            System.out.println("1 -- View given courses");
            System.out.println("2 -- View student list of the given course");
            System.out.println("3 -- Return to previous menu");
            System.out.println("Please enter your option, eq. '1'");
            String option=scanner.next();
            if(option.equals("1")){//View given courses
                showCourseName(name);
            }else if(option.equals("2")){//View student list of the given course
                showStudentCourse();
            }else if(option.equals("3")){//Return to previous menu
                mainStr();
            }else{
                continue;
            }
            professorMain(name);
            break;
        }
    }


    /**
     * 学生端登录
     */
    private static void studentLoginMain(){
        while (true){
            System.out.println("Please enter your username, or type 'q' to quit.");
            String username=scanner.next();
            if (username.equalsIgnoreCase("q")) {
                return; //
            }
            System.out.println("Please enter your password, or type 'q' to quit.");
            String password=scanner.next();
            if (password.equalsIgnoreCase("q")) {
                return; //
            }
            // 使用 Stream 进行匹配和返回对象
            Optional<Student> matchedAccount = studentList.stream()
                    .filter(student -> student.getAccount().equals(username) && student.getPassword().equals(password))
                    .findFirst();
            // 检查是否存在匹配的账号
            if (matchedAccount.isPresent()) {
                System.out.println("--------------------");
                System.out.println("Welcome "+matchedAccount.get().getName());
                System.out.println("--------------------");
                studentMain(matchedAccount.get().getId());
                break;
            } else {
                System.out.println("--------------------");
                System.out.println("Error Password");
                System.out.println("--------------------");
                continue;
            }
        }
    }

    /**
     * 学生端业务
     */
    private static void studentMain(String id) {
        while (true){
            System.out.println("1 -- View all courses");
            System.out.println("2 -- Add courses to your list");
            System.out.println("3 -- View enrolled courses");
            System.out.println("4 -- Drop courses in your list");
            System.out.println("5 -- View grades");
            System.out.println("6 -- Return to previous menu");
            System.out.println("Please enter your option, eq. '1'");
            String option=scanner.next();
            if(option.equals("1")){//View all courses
                showCourse();
            }else if(option.equals("2")){//Add courses to your list
                addStudentCourses(id);
            }else if(option.equals("3")){
                showStudentGrades(id);
            }else if(option.equals("4")){
                deleteCourse();
            }else if(option.equals("5")){
                showGrades(id);
            }else if(option.equals("6")){
                mainStr();
            }else{
                continue;
            }
            studentMain(id);
            break;
        }
    }

    /**
     * 查询自己选择的课程
     * @param id
     */
    private static void showStudentGrades(String id) {
        System.out.println("-------------The course list-----------------");
        Student student=Student.exitStudentId(id,studentList);
        if(student!=null){
            String[] coursescoreid=student.getScoreclassid().split(",");
            for (String s : coursescoreid) {
                String[] couresDto=s.split(":");
                //根据ID在获取选修课名称
                Course course=Course.exitCourseId(couresDto[0].trim(),courseList);
                if(course!=null){
                    System.out.println(couresDto[0].trim()+"|"+course.getCoursename());
                }
            }
        }
    }

    /**
     * 学生添加自己的课程
     */
    private static void addStudentCourses(String userid) {
        String courseid="";
        String username="";
        while (true){
            System.out.println("Please select the course ID you  want to add to your list, eq. 'CIST590'. Or enter 'q' tp return to the preveious menu.");
            courseid=scanner.next();
            if (courseid.equalsIgnoreCase("q")) {
                professorMain(userid);
                break; //
            }
            //检测课程ID是否存在
            Course course=Course.exitCourseId(courseid,courseList);
            if(course!=null){
                System.out.println("The courseid already exist");
                continue;
            }
            //检测当前课程是否自己已经选择过了
            List<Student> student=Student.exitStudentCourseId(userid,studentList);
            if(student!=null&&student.size()>=1){
                System.out.println("The course you selected is already in yourlist");
                continue;
            }
            break;
        }
        System.out.println("Course added successfully");
    }

    /**
     * 查询自己的课程成绩
     * @param id
     */
    private static void showGrades(String id) {
        System.out.println("Here are the courses you already token, with your grade in a letter format ");
        Student student=Student.exitStudentId(id,studentList);
        if(student!=null){
            String[] coursescoreid=student.getScoreclassid().split(",");
            for (String s : coursescoreid) {
                String[] couresDto=s.split(":");
                //根据ID在获取选修课名称
                Course course=Course.exitCourseId(couresDto[0].trim(),courseList);
                if(course!=null){
                    System.out.println("Grade of "+couresDto[0].trim()+" "+course.getCoursename()+"："+couresDto[1]);
                }
            }
        }
    }


}
